<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use Validator;
use Illuminate\Http\Request;
use App\Libraries\Weixin;
use DB;
use Illuminate\Support\Facades\Log;
use EasyWeChat\Foundation\Application;
use QrCode;
use App\Models\QrcodeToken;
use App\Models\User;
use App\Models\Door;
use App\Models\Order;
use App\Models\GoodsNexus;
use App\Models\OrderDetail;
use App\Models\Inform;
use App\Models\Shops;
use Illuminate\Support\Facades\Cache;

class EntranceController extends Controller {

    //二维码页面,需要传参数shop_id,way_type
    public function qrcodeHtml(Request $request) {
        $validator = Validator::make($request->all(), [
                    'shop_id' => 'required|integer',
                    'way_type' => 'required|integer',
        ]);
        if ($validator->fails()) {
            $errorMsg = $validator->errors()->all();
            //如果验证未通过，返回第一条错误信息
            return ['status' => 0, 'msg' => $errorMsg[0]];
        }
        return view('wechat.qrcode', ['shop_id' => $request->input('shop_id'), 'way_type' => $request->input('way_type')]);
    }

    //二维码图片,需要传参数shop_id、way_type
    public function qrCodePng(Request $request) {
        $validator = Validator::make($request->all(), [
                    'shop_id' => 'required|integer',
                    'way_type' => 'required|integer',
                    'random'=>'required'
        ]);
        if ($validator->fails()) {
            $errorMsg = $validator->errors()->all();
            //如果验证未通过，返回第一条错误信息
            return ['status' => 0, 'msg' => $errorMsg[0]];
        }
        $shop_id = $request->input('shop_id');
        $way_type = $request->input('way_type');
        $random = $request->input('random');
//        if (!Cache::has('qrcode.' . $shop_id . '.' . $way_type . '.' . $random)) {
//            Cache::put('qrcode.' . $shop_id . '.' . $way_type . '.' . $random, 1, 1);
//        }
        QrCode::format('png');
        QrCode::size(500);
        header('Content-type: image/png');
        return QrCode::generate(url('check_user?shop_id=' . $shop_id . '&way_type=' . $way_type.'&secret=e10adc3949ba59abbe56e057f20f883e'));
        //return QrCode::generate(url('check_user?shop_id=' . $shop_id . '&way_type=' . $way_type . '&random=' . $random));
    }

    //检查用户是否注册,如果已经注册，则授权进入A门
    public function checkUser(Request $request, Application $wechat) {
        $input = $request->all();
//        if (!Cache::has('qrcode.' . $input['shop_id'] . '.' . $input['way_type'] . '.' . $input['random'])) {
//            return '链接已失效';
//        }
        if($request->input('secret') != 'e10adc3949ba59abbe56e057f20f883e'){
            return '链接已失效';
        }
        if (empty(session('wechat_userinfo'))) {
//            session(['target_url' => 'check_user?shop_id=' . $input['shop_id'] . '&way_type=' . $input['way_type'].'&random='.$input['random']]);
            session(['target_url' => 'check_user?shop_id=' . $input['shop_id'] . '&way_type=' . $input['way_type'].'&secret='.$input['secret']]);
            return $wechat->oauth->scopes(['snsapi_userinfo'])
                            ->redirect();
        }
        $user = User::where('openid', session('wechat_userinfo.openid'))->first();
        //判断是否注册
        if (empty($user)) {
            return redirect('/register');
        }
        $userService = $wechat->user;
        $wechatUser = $userService->get(session('wechat_userinfo.openid'));
        if ($wechatUser->subscribe == 0) {
            return view('wechat.user.subscribe');
        }
        //如果用户有未结账的订单，则不允许进入
        if ($order = Order::where('user_id', $user->id)->where('state', 0)->first()) {
            return redirect('order_list?order_id='.$order->id.'&once=yes');
        }
        $js = $wechat->js;
        //判断该超市AB门之间是否有人中
        if (Door::where('shop_id', $input['shop_id'])->where('way_type', $input['way_type'])->first()) {
            //入口
            if ($input['way_type'] == 1) {
                //提示用户请等待
                return view('wechat.door.wait1', ['js' => $js]);
            } elseif ($input['way_type'] == 2) {
                //提示用户请等待
                return view('wechat.door.wait2', ['js' => $js]);
            }
        }
        //用户进入AB门之间
        Door::create([
            'user_id' => $user->id,
            'shop_id' => $input['shop_id'],
            'way_type' => $input['way_type']
        ]);

        if ($input['way_type'] == 1) {
            //用户进门，欢迎光临
            return redirect('/welcome');
        } elseif ($input['way_type'] == 2) {
            //用户出门，进入rfid扫描区
            return view('wechat.door.scan', ['js' => $js]);
        }
    }

    public function welcome(Application $wechat) {
        if (empty(session('wechat_userinfo'))) {
            session(['target_url' => 'welcome']);
            return $wechat->oauth->scopes(['snsapi_userinfo'])
                            ->redirect();
        }
        $userService = $wechat->user;
        $user = $userService->get(session('wechat_userinfo.openid'));
        return view('wechat.door.welcome', ['userinfo' => session('wechat_userinfo'), 'subscribe' => $user->subscribe]);
    }

    //接受硬件的轮询请求，会接口3个参数：1、商店id(shop_id)  2、入口还是出口(way_type=1是入口，way_type=2是出口)  3、A门还是B门(door_type=A或者B)
    public function checkDoor(Request $request) {
        $validator = Validator::make($request->all(), [
                    'shop_id' => 'required|integer',
                    'way_type' => 'required|integer',
                    'door_type' => 'required|alpha',
        ]);

        if ($validator->fails()) {
            $errorMsg = $validator->errors()->all();
            //如果验证未通过，返回第一条错误信息
            return ['status' => 0, 'msg' => $errorMsg[0]];
        }
        if ($request->input('door_type') != 'A') {
            return ['status' => 0, 'msg' => '只有A门才需要轮询验证'];
        }
        $door = Door::
                where('shop_id', $request->input('shop_id'))
                ->where('way_type', $request->input('way_type'))
                ->first();
        if (empty($door)) {
            return ['status' => 0, 'msg' => '身份验证失败'];
        }
        return ['status' => 1, 'msg' => '身份验证成功'];
    }

    //接受通知
    /*
     * inform_type:door_b
     * way_type:1(入口)
     * door_type:A
     */
    public function inform(Request $request, Application $wechat) {
        $validator = Validator::make($request->all(), [
                    'shop_id' => 'required|integer',
                    'inform_type' => 'required',
                    'secret' => 'required',
        ]);
        if ($validator->fails()) {
            $errorMsg = $validator->errors()->all();
            //如果验证未通过，返回第一条错误信息
            return ['status' => 0, 'msg' => $errorMsg[0]];
        }
        $shop = Shops::find($request->input('shop_id'));
        if (!$shop) {
            return ['status' => 0, 'msg' => '不存在该商店'];
        }
        if ($shop->shop_secret != $request->input('secret')) {
            return ['status' => 0, 'msg' => '秘钥不合法'];
        }
        $inform_type = $request->input('inform_type');
        if ($inform_type != 'rfid' && $inform_type != 'door' && $inform_type != 'scan' && $inform_type != 'nobody') {
            return ['status' => 0, 'msg' => '通知类型错误'];
        }
        switch ($request->input('inform_type')) {
            //门开关状态通知
            case 'door':
                $validator = Validator::make($request->all(), [
                            'way_type' => 'required',
                            'door_type' => 'required',
                            'door_state' => 'required|integer',
                ]);
                if ($validator->fails()) {
                    $errorMsg = $validator->errors()->all();
                    //如果验证未通过，返回第一条错误信息
                    return ['status' => 0, 'msg' => $errorMsg[0]];
                }
                $door_type = $request->input('door_type');
                $way_type = $request->input('way_type');
                if ($door_type != 'A' && $door_type != 'B') {
                    return ['status' => 0, 'msg' => '门类型错误'];
                } elseif ($way_type != 1 && $way_type != 2) {
                    return ['status' => 0, 'msg' => '出入类型错误'];
                }
                //找到对应商店的门，删除该条记录
                if ($request->input('door_type') == 'B' && $request->input('door_state') == '0') {
                    $door = Door::
                            where('shop_id', $request->input('shop_id'))
                            ->where('way_type', $request->input('way_type'))
                            ->delete();
                }
                break;
            //nobody通知
            case 'nobody':
                $validator = Validator::make($request->all(), [
                            'way_type' => 'required'
                ]);
                if ($validator->fails()) {
                    $errorMsg = $validator->errors()->all();
                    //如果验证未通过，返回第一条错误信息
                    return ['status' => 0, 'msg' => $errorMsg[0]];
                }
                $door = Door::
                        where('shop_id', $request->input('shop_id'))
                        ->where('way_type', $request->input('way_type'))
                        ->delete();
                break;
            case 'rfid':
                $validator = Validator::make($request->all(), [
                            'rfid_json' => 'required|JSON'
                ]);
                if ($validator->fails()) {
                    $errorMsg = $validator->errors()->all();
                    //如果验证未通过，返回第一条错误信息
                    return ['status' => 0, 'msg' => $errorMsg[0]];
                }
                $rfid_json = $request->input('rfid_json');
                $rfid_json_arr = json_decode($rfid_json, true);
                //找到正在扫描区的人
                $door = Door::where('shop_id', $request->input('shop_id'))->where('way_type', 2)->first();
                if (empty($door)) {
                    //如果验证未通过，返回第一条错误信息
                    return ['status' => 0, 'msg' => '没有人在扫描区'];
                }
                //接受json格式的rfid数据，事务插入
                DB::beginTransaction();
                try {
                    foreach ($rfid_json_arr['ids'] as $rfid) {
                        $goodsNexus = GoodsNexus::where('rfid', $rfid)->first();
                        if (empty($goodsNexus)) {
                            Log::warning('rfid为' . $rfid . '的商品不存在');
                            continue;
                        } elseif ($goodsNexus->state == 1) {
                            Log::warning('rfid为' . $rfid . '的商品已出售');
                            continue;
                        }
                        $order = Order::where('shop_id', $request->input('shop_id'))
                                ->where('user_id', $door->user_id)
                                ->where('state', 0)
                                ->first();

                        if ($order) {
                            $order->total = $order->total + $goodsNexus->goods->price;
                            $order->amount = $order->amount + 1;
                            $order->save();
                        } else {
                            $order = Order::create([
                                        'shop_id' => $request->input('shop_id'),
                                        'user_id' => $door->user_id,
                                        'order_num' => build_order_no(),
                                        'total' => $goodsNexus->goods->price,
                                        'amount' => 1,
                                        'state' => 0
                            ]);
                        }
                        $goodsNexus->state = 1;
                        $goodsNexus->save();

                        OrderDetail::create([
                            'order_id' => $order->id,
                            'rfid' => $rfid
                        ]);
                    }
                } catch (\Exception $e) {
                    DB::rollback(); //事务回滚
                    Log::error($e->getMessage());
                    return ['status' => 0, 'msg' => $e->getMessage()];
                }
                DB::commit();
                if (!empty($order->total)) {
                    $pushState = $this->pushOrder($order, $wechat);
                }
                break;
        }
        $data = [
            'shop_id' => $request->input('shop_id'),
            'inform_type' => $request->input('inform_type'),
            'way_type' => empty($request->input('way_type')) ? null : $request->input('way_type'),
            'door_type' => empty($request->input('door_type')) ? null : $request->input('door_type'),
            'door_state' => empty($request->input('door_state')) ? null : $request->input('door_state'),
            'scan_state' => empty($request->input('scan_state')) ? null : $request->input('scan_state'),
            'ip' => $request->ip()
        ];
        try {
            Inform::create($data);
            return ['status' => 1, 'msg' => '接受通知成功'];
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return ['status' => 0, 'msg' => '接受通知异常：' . $e->getMessage()];
        }
    }

    public function pushOrder($order, $wechat) {
        $user = User::find($order->user_id);
        $notice = $wechat->notice;
        $userId = $user->openid;
        $templateId = 'fiOrLTDfvWIhqOdlovgFFT5N7SVIDBuPaqlLHbAlvnU';
        $url = env('APP_URL') . '/order_list?order_id=' . $order->id;
        $data = array(
            "keyword1" => $order->order_num,
            //'keyword2' => '无人超市商品',
            "keyword2" => (string) $order->updated_at,
            "remark" => "欢迎再次购买！",
        );
        $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();
        if ($result['errcode'] === 0) {
            Log::info('订单号为' . $order->order_num . '的订单推送成功');
            return true;
        } else {
            Log::info('订单号为' . $order->order_num . '的订单推送失败');
            Log::info($result);
            return false;
        }
    }

    public function rfidReceive(Request $request, Application $wechat) {
        $data_string = file_get_contents("php://input");
        //dd($data_string);
        if (empty(json_decode($data_string))) {
            return ['status' => 0, 'msg' => 'json格式不正确'];
        }
        $data_json = json_decode($data_string, true);
        $validator = Validator::make($data_json, [
                    'IsSuccessed' => 'required|integer',
                    'Message' => 'required',
                    'Data' => 'required|array',
        ]);
        if ($validator->fails()) {
            $errorMsg = $validator->errors()->all();
            //如果验证未通过，返回第一条错误信息
            return ['status' => 0, 'msg' => $errorMsg[0]];
        }
        if ($data_json['IsSuccessed'] != true) {
            return ['status' => 0, 'msg' => '操作失败'];
        }
        $data = [
            'shop_id' => 1,
            'inform_type' => 'rfid',
            'ip' => $request->ip()
        ];
        log::info($data_string);
        try {
            $inform = Inform::create($data);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
        }
        //找到正在扫描区的人
        $door = Door::where('shop_id', 1)->where('way_type', 2)->first();
        if (empty($door)) {
            //如果验证未通过，返回第一条错误信息
            $res = ['status' => 0, 'msg' => 'No one is in the scanning area']; //没有人在扫描区
            //$inform->return_json = json_encode($res);
            //$inform->save();
            Log::info('没有人在扫描区');
            return $res;
        }
        $errorRfid = [];
        $successRfid = [];
        //接受json格式的rfid数据，事务插入
        //DB::beginTransaction();
        //try {
        foreach ($data_json['Data'] as $key => $rfid) {
            $goodsNexus = GoodsNexus::where('rfid', $rfid)->first();
            if (empty($goodsNexus)) {
                //Log::warning('rfid为' . $rfid . '的商品不存在');
                $errorRfid[$key]['rfid'] = $rfid;
                $errorRfid[$key]['reason'] = 'Merchandise does not exist'; //商品不存在

                continue;
            } elseif ($goodsNexus->state == 1) {
                //Log::warning('rfid为' . $rfid . '的商品已出售');
                $errorRfid[$key]['rfid'] = $rfid;
                $errorRfid[$key]['reason'] = 'The goods have been sold'; //商品已出售
                continue;
            }
            $successRfid[] = $rfid;
            $order = Order::where('shop_id', 1)
                    ->where('user_id', $door->user_id)
                    ->where('state', 0)
                    ->first();
            if ($order) {
                $order->total = $order->total + $goodsNexus->goods->price;
                $order->amount = $order->amount + 1;
                $order->save();
            } else {
                //dd($goodsNexus->goods);
                $order = Order::create([
                            'shop_id' => 1,
                            'user_id' => $door->user_id,
                            'order_num' => build_order_no(),
                            'total' => $goodsNexus->goods->price,
                            'amount' => 1,
                            'state' => 0
                ]);
            }
            $goodsNexus->state = 1;
            $goodsNexus->save();

            OrderDetail::create([
                'order_id' => $order->id,
                'rfid' => $rfid
            ]);
        }
        //} catch (\Exception $e) {
        //	DB::rollback(); //事务回滚
        //	Log::error($e->getMessage());
        //	return ['status' => 0, 'msg' => $e->getMessage()];
        //}
        //DB::commit();
        if (!empty($order->total)) {
            $pushState = $this->pushOrder($order, $wechat);
            if ($pushState) {
                $res = ['status' => 1, 'msg' => 'Successful order push', 'success' => $successRfid, 'warn' => $errorRfid]; //订单推送成功
                //$inform->return_json = json_encode($res);
                //$inform->save();
                Log::warning($res);
                return $res;
            } else {
                $res = ['status' => 0, 'msg' => 'Failed order push']; //订单推送失败
                //$inform->return_json = json_encode($res);
                //$inform->save();
                Log::warning($res);
                return $res;
            }
        } else {
            $res = ['status' => 0, 'msg' => 'Order push exception', 'error' => $errorRfid]; //订单推送异常
            //$inform->return_json = json_encode($res);
            //$inform->save();
            Log::warning($res);
            return $res;
        }
    }

}
